﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.TaskRuntime
{
    public class RTParameterContext : IDisposable
    {
        Noesis.Javascript.JavascriptContext _jsContext;
        public void Open()
        {
            _jsContext = new Noesis.Javascript.JavascriptContext();
            try
            {
                _jsContext.Run("1+1");
                Init();
                Logger.InfoToTag("JSEngine", "Try1: OK");
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorToTag("JSEngine", "Try1:" + ex.Message);
                _jsContext = new Noesis.Javascript.JavascriptContext();
            }

            try
            {
                _jsContext.Run("1+1");
                Init();
                Logger.InfoToTag("JSEngine", "Try2: OK");
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorToTag("JSEngine", "Try2:" + ex.Message);
                _jsContext = new Noesis.Javascript.JavascriptContext();
            }

            try
            {
                _jsContext.Run("1+1");
                Init();
                Logger.InfoToTag("JSEngine", "Try3: OK");
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorToTag("JSEngine", "Try3:" + ex.Message);
                _jsContext = null;
            }
        }

        public void Close()
        {
            if(_jsContext != null)
            {
                _jsContext.Dispose();
            }
        }
        
        private void Init()
        {
            _jsContext.SetParameter("DateTime", new DateScriptObj());
        }

        public string Run(string expression)
        {
            if(_jsContext!=null)
            {
                Logger.InfoToTag("JSEngine", "run:" + expression);
                object retValue = _jsContext.Run(expression);
                if(retValue != null)
                {
                    return retValue.ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }

        public void Dispose()
        {
            Close();
        }
    }
}
